package com.podium.handle;

import com.podium.comment.AjaxResult;
import com.podium.comment.exceptional.BaseException;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import java.util.Optional;

/**
 * @author 邵文泽
 * @description TODO
 * @date 2025/4/14 11:10
 */
@Log4j2
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(BaseException.class)
    public AjaxResult<Void> baseException(BaseException ex) {
        return new AjaxResult<Void>().error(ex.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult<Void> methodArgumentNotValidException(MethodArgumentNotValidException ex) {
        Optional<FieldError> fieldErrorOptional = ex.getBindingResult().getFieldErrors().stream().findFirst();
        if (fieldErrorOptional.isEmpty()) {
            return new AjaxResult<Void>().error("参数错误");
        }
        String defaultMessage = fieldErrorOptional.get().getDefaultMessage();
        return new AjaxResult<Void>().error(defaultMessage);
    }

    @ResponseBody
    @ExceptionHandler(NullPointerException.class)
    public AjaxResult<Void> nullException(NullPointerException ex) {
        log.error("空指针异常", ex);
        return new AjaxResult<Void>().error("数据出现空值，请联系管理员处理！");
    }

    @ResponseBody
    @ExceptionHandler(NoResourceFoundException.class)
    public AjaxResult<Void> noResourceFoundException(NoResourceFoundException ex) {
//        log.error("系统异常", ex);
        return new AjaxResult<Void>().error("接口不存在！");
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public AjaxResult<Void> exception(Exception ex) {
        log.error("系统异常", ex);
        return new AjaxResult<Void>().error("系统异常，请联系管理员处理！");
    }

}
